package com.superhelper.processor.order.consumer;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.superhelper.common.domain.DeliverRecord;
import com.superhelper.common.domain.PushMsgType;
import com.superhelper.common.domain.TakeOutOrder;

@Component
public class UnReceiverOrderTask extends AbstractOrderConsumer {
    private static final Logger log = LoggerFactory.getLogger(UnReceiverOrderTask.class);

    @Value("${online}")
    private boolean online;

    /**
     * 未接单推送
     */
    // @Scheduled(cron = "0 */1 * * * ?")
    // public void run() {
    // log.info("getUnReceiverOrder start-{}", online);
    // if (online) {
    // List<TakeOutOrder> list = orderMapper.getUnReceiverOrder();
    // Map<String, String> map = new HashMap<String, String>();
    // for (TakeOutOrder order : list) {
    // try {
    // PushMsgType msgType = getPushMsgTypeByStatus(order.getStatus());
    // if (msgType.equals(PushMsgType.ORDER_CREATED)) {
    // publish(order, msgType, true);
    // } else if (!map.containsKey(msgType.getValue())) {// 异常单、取消单只推一次
    // map.put(msgType.getValue(), msgType.getValue());
    // publish(order, msgType, true);
    // }
    // } catch (Exception e) {
    // log.error("UnReceiverOrderTask error :{}", e);
    // }
    // }
    // log.info("getUnReceiverOrder end :size:{}", list.size());
    // }
    // }

    /**
     * 异常配送单推送
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void runDelivers() {

        log.info("getAbnormalOrderList start-{}", online);
        if (online) {
            List<DeliverRecord> listDelivers = deliverRecordMapper.getAbnormalOrderList();
            for (DeliverRecord d : listDelivers) {
                TakeOutOrder order = orderMapper.getById(d.getOrderId());
                if (order != null) {
                    publish(order, PushMsgType.DELIVER_EXCEPTION, true);
                }
            }
            log.info("getAbnormalOrderList end :size:{}", listDelivers.size());
        }
    }

    public PushMsgType getPushMsgTypeByStatus(String status) {
        switch (status) {
        case "unprocessed":
            return PushMsgType.ORDER_CREATED;
        case "refunding":
            return PushMsgType.ORDER_REFUND;
        case "apply_cancel":
            return PushMsgType.ORDER_CANCELED;
        default:
            return PushMsgType.UNKNOWN;
        }
    }
}
